<template>
	<view class="add-station">
		<navBar :isBackGround="false">
			<template v-slot:center>
				<view class="nav_center">添加电站</view>
			</template>
			<template v-slot:left>
				<text class="cancel-add" @click="cancelAdd">取消</text>
			</template>
		</navBar>
		<view class="form-content">
			<view class="form-item top-item">
				<view class="title">电站封面</view>
				<image src="/static/img/default.png" alt="封面" class="cover" @click="uploadCover"></image>
			</view>
			<view class="form-item" @click="goMap">
				<view class="title">位置</view>
				<view class="right">
					<view class="">
						<view v-if="addForm.longitude">经度:{{ addForm.longitude }}</view>
						<view v-if="addForm.latitude">纬度:{{ addForm.latitude }}</view>
					</view>
					<text class="iconfont icon-zhizhen"></text>
				</view>
			</view>
			<view class="form-item">
				<view class="title">电站名称</view>
				<input class="uni-input" placeholder="必填" v-model="addForm.stationName" />
			</view>
			<view class="form-item">
				<!-- countryId+provinceId+cityId+countyId -->
				<view class="title">区域</view>
				<view class="right">
					<!-- <input class="uni-input" placeholder="必填" v-model="addForm.region" /> -->
					<!-- <text class="iconfont icon-zhizhen" @click="openRegion"></text> -->
					<!-- 地区选择器 -->
					<uni-data-picker ref="data_picker" placeholder="请选择区域" popup-title="请选择区域" :localdata="dataTree"
						v-model="classes" @nodeclick="onnodeclick">
					</uni-data-picker>
				</view>
			</view>
			<view class="form-item">
				<view class="title">地址</view>
				<input class="uni-input" placeholder="必填" v-model="addForm.address" />
			</view>
			<!-- <view class="form-item">
				<view class="title">装机容量（kWp）</view>
				<input class="uni-input" placeholder="必填" v-model="addForm.capacity" />
			</view>
			<view class="form-item">
				<view class="title">计划发电量</view>
				<input class="uni-input" placeholder="必填" v-model="addForm.planPower" />
			</view> -->
			<view class="form-radio-item">
				<view class="title">系统类型 
					<text class="iconfont icon-yiwen" @click="openDesc_system"></text>
				</view>
				<view class="uni-list">
					<radio-group @change="radioChange_system">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in system_items"
							:key="item.value">
							<view>
								<radio :value="item.value" color="#3f8cf7" :checked="index === current_radio_system"
									style="transform: scale(0.7)" />
							</view>
							<view>{{ item.name }}</view>
						</label>
					</radio-group>
				</view>
				<!-- 系统类型弹窗 -->
				<uni-popup ref="popup_system" type="center" class="system-popup">
					<view class="system-popup-container">
						<view class="desc-title">系统类型</view>
						<view class="desc-content">
							系统类型决定该系统有哪些核心数据，比如“光伏+电网”有发电数据，“光伏+电网+用电”在“光伏+电网”的基础上增加并网和购电数据，用电负载数据，“光伏+电网+用电+储能”又在“光伏+电网+用电”的基础上增加了充电和放电数据，不同的系统类型将会展示不同的数据看板，请根据实际情况选择正确的系统类型。
						</view>
						<view class="desc-btn" @click="closeSystemDesc">我知道了</view>
					</view>
				</uni-popup>
			</view>
			<view class="form-radio-item bottom-item">
				<view class="title">电站类型
					<text class="iconfont icon-yiwen" @click="openDesc_station"></text>
				</view>
				<!-- 电站类型弹窗 -->
				<uni-popup ref="popup_station" type="center" class="system-popup">
					<view class="system-popup-container">
						<view class="desc-title">电站类型</view>
						<view class="desc-content">
							电站类型用于区分不同类型的电站形态，不同的电站类型会展示不同的数据看板，请根据实际情况选择正确的电站类型。
						</view>
						<view class="desc-btn" @click="closeStationDesc">我知道了</view>
					</view>
				</uni-popup>
				<view class="uni-list">
					<radio-group @change="radioChange_station">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in station_items"
							:key="item.value">
							<view>
								<radio :value="item.value" color="#3f8cf7" :checked="index === current_radio_station"
									style="transform: scale(0.7)" />
							</view>
							<view>{{ item.name }}</view>
						</label>
					</radio-group>
				</view>
			</view>
			<!-- 角度 -->
			<!-- <view class="form-item top-item">
				<view class="title">方位角(°)<text class="iconfont icon-yiwen" @click="openDesc_azimuth" /></view>
				<input class="uni-input" placeholder="选填,0-360°" v-model="addForm.azimuth" />
				<uni-popup ref="popup_azimuth" type="center" class="system-popup">
					<view class="system-popup-container">
						<view class="desc-title">方位角</view>
						<view class="desc-content">
							方位角用于分析电站发电质量，请根据实际情况填写
						</view>
						<view class="desc-btn" @click="closeAzimuth">我知道了</view>
					</view>
				</uni-popup>
			</view>
			<view class="form-item">
				<view class="title">倾角(°)<text class="iconfont icon-yiwen" @click="openDesc_dipAngle" /></view>
				<input class="uni-input" placeholder="选填,0-90°" v-model="addForm.dipAngle" />
				<uni-popup ref="popup_dipAngle" type="center" class="system-popup">
					<view class="system-popup-container">
						<view class="desc-title">倾角</view>
						<view class="desc-content">
							倾角用于分析电站发电质量，请根据实际情况填写
						</view>
						<view class="desc-btn" @click="closeDipAngle">我知道了</view>
					</view>
				</uni-popup>
			</view> -->
			<!-- <view class="form-item ">
				<view class="title">并网日期<text class="iconfont icon-yiwen" @click="openDesc_date" /></view>
				<view class="right">
					<input class="uni-input" placeholder="" v-model="addForm.mergeTime" />
					<text class="iconfont icon-zhizhen" @click="open_date"></text>
					<uni-popup ref="popup_desc_date" type="center" class="system-popup">
						<view class="system-popup-container">
							<view class="desc-title">并网日期</view>
							<view class="desc-content">
								用于确定电站何时并网，可在筛选项中筛选“已并网”和“未并网”的电站
							</view>
							<view class="desc-btn" @click="closeDateDesc">我知道了</view>
						</view>
					</uni-popup>
					<uni-popup ref="popup_date" type="bottom" class="date-popup" :mask-click="false">
						<view class="top-btn">
							<view class="cancel" @click="cancel_date">取消</view>
							<view class="confirm" @click="confirm_date">确定</view>
						</view>
						<picker-view v-if="visible" :indicator-style="indicatorStyle" :value="value"
							@change="bindChange" class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item, index) in years" :key="index">{{ item }}年</view>
							</picker-view-column>
							<picker-view-column>
								<view class="item" v-for="(item, index) in months" :key="index">{{ item }}月</view>
							</picker-view-column>
							<picker-view-column>
								<view class="item" v-for="(item, index) in days" :key="index">{{ item }}日</view>
							</picker-view-column>
						</picker-view>
					</uni-popup>
				</view>
			</view> -->
			<!-- <view class="form-item">
				<view class="title">时区</view>
				<view class="right">
					<input class="uni-input" placeholder="" v-model="addForm.timeZone" />
					<text class="iconfont icon-zhizhen"></text>
				</view>
			</view> -->
			<!-- <view class="form-item top-item">
				<view class="title">货币单位</view>
				<view class="right">
					<input class="uni-input" placeholder="元" v-model="addForm.currencyUnit" />
					<text class="iconfont icon-zhizhen"></text>
				</view>
			</view> -->
			<view class="form-item">
				<view class="title">度电收益(元/kWh)</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.unitPrice" />
			</view>
			<view class="form-item">
				<view class="title">总成本(元)</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.cost" />
			</view>
			<view class="form-item">
				<view class="title">电站管理员</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.stationAdmin" />
			</view>
			<view class="form-item bottom-item">
				<view class="title">管理员电话</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.adminTel" />
			</view>
			<view class="form-item top-item">
				<view class="title">业主姓名</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.merchantName" />
			</view>
			<view class="form-item">
				<view class="title">联系电话</view>
				<input class="uni-input" placeholder="选填,用于APP内拨打电话" v-model="addForm.telPhone" />
			</view>
			<view class="form-item bottom-item">
				<view class="title">工作单位</view>
				<input class="uni-input" placeholder="选填" v-model="addForm.company" />
			</view>
			<button style="margin: 20rpx" type="primary" @click="saveAdd">
				保存
			</button>
		</view>
	</view>
</template>

<script>
	import {
		saveAddForm,
		getRegionData
	} from "@/common/api/api.js"
	import navBar from "@/components/navbar/index.vue"
	export default {
		components: {
			navBar,
		},
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			for (let i = 1990; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}
			return {
				title: "picker-view",
				years,
				year,
				months,
				month,
				days,
				day,
				classes: "0",
				dataTree: [],
				visible: true,
				value: [9999, month - 1, day - 1],
				indicatorStyle: `height: 50px;`,
				current_radio_system: 0,
				current_radio_station: 0,
				station_items: [{
						value: "1",
						name: "分布式户用",
						checked: "true",
					},
					{
						value: "2",
						name: "分布式商业",
					},
					{
						value: "3",
						name: "分布式工业",
					},
					{
						value: "4",
						name: "地面电站",
					},
				],
				system_items: [{
						value: "1",
						name: "光伏+电网",
						checked: "true",
					},
					{
						value: "2",
						name: "光伏+电网+用电",
					},
					{
						value: "3",
						name: "光伏+电网+用电+储能",
					},
				],
				addForm: {
					latitude: "",
					longitude: "",
					latdegree: "",
					latpoints: "",
					latseconds: "",
					lngdegree: "",
					lngpoints: "",
					lngseconds: "",
					//planPower: "",
					stationName: "",
					countryId: "",
					cityId: "",
					provinceId: "",
					address: "",
					//capacity: "",
					currencyUnit: "元",
					unitPrice: "",
					cost: "",
					merchantName: "",
					company: "",
					telPhone: "",
					token: "",
					type: 1,
				},
			}
		},
		methods: {
			//上传封面图片
			uploadCover() {
				//   uni.chooseImage({
				//     count: 1, //默认9
				//     sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				//     sourceType: ['album'], //从相册选择
				//     loop: true,
				//     success: res => {
				//       console.log(res);
				//       if (res.tempFilePaths.length != 0) {
				//         this.addForm.coverImg = res.tempFilePaths[0]
				//       }
				//       console.log(JSON.stringify(res.tempFilePaths));
				//       // var tempFilePaths = res.tempFilePaths;
				//       // console.log(tempFilePaths);
				//       // console.log(tempFilePaths[0]);
				//       uni.uploadFile({
				//         url: 'https://pv.solar.chu.edu.cn/station/uploadFile',
				//         filePath: tempFilePaths[0],
				//         name: 'file',
				//         success: uploadFileRes => {
				//           console.log('上传图片', JSON.parse(uploadFileRes.data));
				//         },
				//         fail(err) {
				//           console.log(err);
				//         }
				//       });
				//     }
				//   });
			},

			cancelAdd() {
				uni.navigateBack()
			},
			getNowDate() {
				var date = new Date()
				var year = date.getFullYear() // 年
				var month = date.getMonth() + 1 // 月
				var day = date.getDate() // 日
				if (month >= 1 && month <= 9) {
					month = "0" + month
				}
				if (day >= 0 && day <= 9) {
					day = "0" + day
				}
				return year + "-" + month + "-" + day
			},
			open_date() {
				this.$refs.popup_date.open("bottom")
			},
			openDesc_date() {
				this.$refs.popup_desc_date.open("center")
			},
			closeDateDesc() {
				this.$refs.popup_desc_date.close()
			},
			// 日期选择器触发
			bindChange: function(e) {
				const val = e.detail.value
				this.year = this.years[val[0]]
				this.month = this.months[val[1]]
				this.day = this.days[val[2]]
			},
			bindChange_region(e) {
				const val = e.detail.value
				this.city
				console.log("value", val)
			},
			// 取消日期选择
			cancel_date() {
				this.$refs.popup_date.close()
			},
			// 确定日期选择
			confirm_date() {
				this.addForm.mergeTime = this.year + "-" + this.month + "-" + this.day
				this.$refs.popup_date.close()
			},
			//系统类型弹窗说明
			openDesc_system() {
				this.$refs.popup_system.open("center")
			},
			closeSystemDesc() {
				this.$refs.popup_system.close()
			},
			// 电站类型弹窗说明
			openDesc_station() {
				this.$refs.popup_station.open("center")
			},
			closeStationDesc() {
				this.$refs.popup_station.close()
			},
			//方位角弹窗说明
			openDesc_azimuth() {
				this.$refs.popup_azimuth.open("center")
			},
			closeAzimuth() {
				this.$refs.popup_azimuth.close()
			},
			//倾角弹窗说明
			openDesc_dipAngle() {
				this.$refs.popup_dipAngle.open("center")
			},
			closeDipAngle() {
				this.$refs.popup_dipAngle.close()
			},

			radioChange_system: function(evt) {
				for (let i = 0; i < this.system_items.length; i++) {
					if (this.system_items[i].value === evt.detail.value) {
						this.current_radio_system = i
						break
					}
				}
			},
			radioChange_station: function(evt) {
				for (let i = 0; i < this.station_items.length; i++) {
					if (this.station_items[i].value === evt.detail.value) {
						this.current_radio_station = i
						break
					}
				}
			},
			//经纬度转换度分秒
			transformLocation(coordinates) {
				// 坐标字符串转数组
				const coords = String(coordinates).split(".")
				// 度  获取数组第一位
				const degree = coords[0]
				// 通过数组第二位进行计算生成数组获取分
				const mArr = String(Number(String(0 + "." + coords[1])) * 60).split(".")
				// 分 获取数组第一位
				const minute = mArr[0]
				// 秒 通过获取数组第二位进行计算生成秒  截取小数点后两位
				const second = (Number(String(0 + "." + mArr[1])) * 60).toFixed()
				// 结果
				return {
					degree,
					minute,
					second,
				}
				// const result = [degree + "°", minute + "′", second + "″"];
				// return result.join('');
			},
			//请求区域地址
			async getRegion() {
				const token = uni.getStorageSync("Token")
				let res = await getRegionData({
					parentId: 0,
					token,
				})
				let level = 0
				res.data.forEach((item) => {
					let tree = {
						text: item.areaName,
						value: item.id,
						level: level++,
						children: [],
					}
					this.dataTree.push(tree)
				})
			},
			async getNodeData(e) {
				this.classes = e.value
				this.$refs.data_picker.show()
				let l = e.level + ""
				//市
				if (l === "undefined") {
					this.$nextTick(() => {
						this.addForm.cityId = e.value
					})
					return
				}
				const token = uni.getStorageSync("Token")
				let res = await getRegionData({
					token,
					parentId: e.value,
				})
				//省
				if (l.indexOf("-") !== -1) {
					this.addForm.provinceId = e.value
					let i1 = l.split("-")[0]
					let i2 = l.split("-")[1]
					let level = 0
					res.data.forEach((ele) => {
						let tree = {
							text: ele.areaName,
							value: ele.id,
							children: [],
						}
						this.dataTree[i1].children[i2].children.push(tree)
					})
					return
				}
				//国
				if (l.indexOf("-") === -1) {
					this.addForm.countryId = e.value
					let level = 0
					res.data.forEach((ele) => {
						let tree = {
							text: ele.areaName,
							value: ele.id,
							level: l + "-" + level++,
							children: [],
						}
						this.dataTree[l].children.push(tree)
					})
				}
			},
			//区域节点选择
			onnodeclick(e) {
				this.getNodeData(e)
			},
			//保存
			async saveAdd() {
				this.addForm.systemType =
					this.system_items[this.current_radio_system].value * 1
				this.addForm.stationType =
					this.station_items[this.current_radio_station].value * 1
				const latitude = this.transformLocation(this.addForm.latitude)
				const longitude = this.transformLocation(this.addForm.longitude)
				this.addForm.lngdegree = longitude.degree
				this.addForm.lngpoints = longitude.minute
				this.addForm.lngseconds = longitude.second
				this.addForm.latdegree = latitude.degree
				this.addForm.latpoints = latitude.minute
				this.addForm.latseconds = latitude.second
				this.addForm.token = uni.getStorageSync("Token")
				const now = new Date()
				const hour = now.getHours()
				const minutes = now.getMinutes()
				const second = now.getSeconds()
				//this.addForm.createTime = this.addForm.createTime // + " " + hour + ":" + minutes + ":" + second
				// this.addForm.mergeTime = this.addForm.mergeTime + " " + hour + ":" + minutes + ":" + second
				console.log(this.addForm)
				let isSub = Object.values(this.addForm).every((item) => item !== "")
				if (isSub) {
					await saveAddForm(this.addForm)
					if (this.path === "home") {
						uni.switchTab({
							url: "/pages/tabbar/home/index",
						})
					} else {
						uni.switchTab({
							url: "/pages/tabbar/monitor/index",
						})
					}
				} else {
					uni.showToast({
						icon: "none",
						title: "请填写完整信息！",
					})
				}
			},
			//取消保存
			cancelAdd() {
				if (this.path === "home") {
					uni.switchTab({
						url: "/pages/tabbar/home/index",
					})
				} else {
					uni.switchTab({
						url: "/pages/tabbar/monitor/index",
					})
				}
			},
			//跳转地图页
			goMap() {
				uni.navigateTo({
					url: "/pages/stations/map/index",
				})
			},
		},
		onReady() {
			uni.getLocation({
				geocode: true,
				type: "gcj02",
				success: (data) => {
					const {
						address
					} = data
					let lcoation = ""
					if (address) {
						lcoation = Object.values(address).join("")
					}
					address && (this.addForm.address = lcoation || "")
					address && (this.addForm.region = "中国" + address.province || "")
					this.addForm.latitude = data.latitude
					this.addForm.longitude = data.longitude
				},
			})
		},
		onLoad(e) {
			if (e.path) {
				this.path = e.path
			}
			this.getRegion()
			//接受地图页面传来的值
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on("getMapParams", (data) => {
				data.address && (this.addForm.address = data.address || "")
				data.address &&
					(this.addForm.region = "中国" + data.address.split("省")[0] || "")
				setTimeout(() => {
					data.latitude && (this.addForm.latitude = data.latitude)
					data.longitude && (this.addForm.longitude = data.longitude)
				}, 500)
			})
		},
	}
</script>

<style lang="scss" scoped>
	/deep/ .uni-data-tree .input-value .uni-icons {
		font-size: 40rpx !important;
		margin-left: 10rpx !important;
	}

	/deep/ .uni-data-tree {
		right: -20rpx !important;
	}

	/deep/ .uni-data-tree .input-value {
		border: none !important;
	}

	/deep/ .uni-data-tree .input-value .placeholder {
		font-size: 32rpx;
	}

	/deep/.uni-popup .uni-popup__wrapper {
		background: #fff !important;
	}

	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.uni-label-pointer {
		display: flex;
		padding: 6rpx 0;
		align-items: center;
	}

	.icon-yiwen {
		margin-left: 10rpx;
	}

	.uni-input-placeholder {
		color: #999;
	}

	.uni-input {
		text-align: right;
	}

	.nav_center {
		font-weight: bold;
		color: #333;
		font-size: 32rpx;
	}

	.save-add {
		color: #3f8cf7;
		font-size: 28rpx;
	}

	.form-content {
		padding-bottom: 40rpx;
	}

	.cancel-add {
		color: $font_color;
		font-size: 28rpx;
	}

	.top-item {
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		margin-top: 20rpx;
	}

	.bottom-item {
		border-bottom-left-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
		border-bottom: none !important;
	}

	.form-radio-item {
		background-color: #fff;
		margin-left: 20rpx;
		margin-right: 20rpx;
		border-bottom: 2rpx solid $border_bt;
		padding: 30rpx;
		color: $font_color;

		.title {
			margin-bottom: 30rpx;
		}
	}

	.form-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
		border-bottom: 2rpx solid $border_bt;
		padding: 30rpx;
		color: #666;
		margin-left: 20rpx;
		margin-right: 20rpx;

		.title {
			color: #666;
		}

		// font-size: 24rpx;
		.cover {
			width: 200rpx;
			height: 200rpx;
			border-radius: 20rpx;
		}

		.right {
			// font-size: 24rpx;
			display: flex;
			align-items: center;

			.iconfont {
				margin-left: 20rpx;
			}
		}
	}

	.date-popup {
		.top-btn {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 40rpx;
			background-color: #f4f4f4;

			.confirm {
				color: #3f8cf7;
			}
		}

		.picker-view {
			height: 400rpx;
		}
	}

	.system-popup {
		/deep/.uni-popup__wrapper {
			border-radius: 20rpx !important;
		}

		.system-popup-container {
			width: 600rpx;
			border-radius: 20rpx;
			background: #fff;

			.desc-title {
				color: #333;
				font-weight: 600;
				text-align: center;
				padding-top: 20rpx;
				padding-bottom: 10rpx;
			}

			.desc-content {
				padding: 20rpx 40rpx;
			}

			.desc-btn {
				padding: 20rpx 40rpx;
				color: #3f8cf7;
				text-align: center;
				font-size: 32rpx;
				border-top: 2rpx solid $border_bt;
			}
		}
	}
</style>